package models

import (
	"errors"
	"strconv"
	"time"

	"github.com/astaxie/beego/orm"

	_ "github.com/go-sql-driver/mysql"
)

// OSList - all OSinfo combin
var (
	OSList map[string]*OSinfo
)

func init() {
	maxIdle := 5
	maxConn := 100
	// set default database
	orm.RegisterDataBase("default", "mysql", "gocmdb:sf123456@tcp(192.168.50.51:3306)/gocmdb?charset=utf8&loc=Asia%2FShanghai", maxIdle, maxConn)
	// register model
	orm.RegisterModel(new(OSinfo))
	// create table
	orm.RunSyncdb("default", false, true)

	OSList = make(map[string]*OSinfo)

	o := orm.NewOrm()
	var tmplist []*OSinfo
	qs := o.QueryTable("osinfo")
	_, err := qs.All(&tmplist)
	if err != nil {
		panic(err)
	}
	for _, value := range tmplist {
		OSList[value.ID] = value
	}
}

// OSinfo - operating system model
type OSinfo struct {
	ID        string    `orm:"pk;column(id)"`
	Arch      string    `orm:"size(64)"`
	Type      string    `orm:"size(64)"`
	Vendor    string    `orm:"size(64)"`
	Version   string    `orm:"size(64)"`
	Hostname  string    `orm:"size(64)"`
	HostIP    string    `orm:"unique;column(hostip)"`
	Timestamp time.Time `orm:"auto_now;type(datetime)"`
}

// TableName -  define table name
func (o *OSinfo) TableName() string {
	return "osinfo"
}

// AddOS - add a new OS
func AddOS(o OSinfo) string {
	o.ID = "OS_" + strconv.FormatInt(time.Now().UnixNano(), 10)
	o.Timestamp = time.Now()
	OSList[o.ID] = &o
	orm := orm.NewOrm()
	_, err := orm.Insert(&o)
	if err != nil {
		return "Insert failed"
	}
	return o.ID
}

// GetOS - query OS
// 需注意：这里没有数据库查询逻辑，如在运行期间通过后台导入数据，则需要重启应用才能读入内存，方能被查询
func GetOS(oid string) (o *OSinfo, err error) {
	if o, ok := OSList[oid]; ok {
		return o, nil
	}
	return nil, errors.New("OS not found")
}

// func GetAllUsers() map[string]*User {
// 	return UserList
// }

// GetAllOS - return all OS objects
func GetAllOS() map[string]*OSinfo {
	return OSList
}

// UpdateOS - update a OS
func UpdateOS(oid string, oo *OSinfo) (a *OSinfo, err error) {
	if o, ok := OSList[oid]; ok {
		if oo.Arch != "" {
			o.Arch = oo.Arch
		}
		if oo.Type != "" {
			o.Type = oo.Type
		}
		if oo.Vendor != "" {
			o.Vendor = oo.Vendor
		}
		if oo.Version != "" {
			o.Version = oo.Version
		}
		if oo.Version != "" {
			o.Version = oo.Version
		}
		if oo.Hostname != "" {
			o.Hostname = oo.Hostname
		}
		if oo.HostIP != "" {
			o.HostIP = oo.HostIP
		}

		o.Timestamp = time.Now()
	}
	return nil, errors.New("OS not found")
}

// DeleteOS - delete a os object
func DeleteOS(oid string) {
	delete(OSList, oid)
}
